<?php
namespace app\common\service;

use app\common\util\Util;
use think\Model;
use think\Config;
use think\Request;
use Hooklife\ThinkphpWechat\Wechat;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use app\common\service\UserService;
use app\common\model\StoreWeixin;
use app\common\model\UserIntegral;
use app\common\helper\WeixinHelper;

class WeixinService extends BaseService
{
    protected $sid;
    protected $wechat;

    /**
     * 这里设置微信的配置
     * WeixinService constructor.
     */
    public function __construct()
    {
    }

    /**
     * 返回微信对象
     * 读取sid参数实例的对象
     * @param $sid
     * @return Application
     */
    public function get_wechat($sid, $config = null)
    {

        return WeixinHelper::get_wechat($sid, $config);
    }

    /**
     * 获得access_token，整个系统只能用这个函数获得，避免引起混乱导致access_token失效
     * @param $sid
     */
    public function get_access_token($sid)
    {
        $access_token = WeixinHelper::get_access_token($sid);
        return $access_token;
    }

    public function get_user($sid, $openid)
    {
        $user_info = WeixinHelper::get_user_info($sid, $openid);

        return $user_info;
    }

    /**
     * 微信回调获得的用户信息
     * @param $user
     * @return \app\common\model\User
     */
    public function edit_user($sid, $user)
    {
        $user_service = new UserService();
        $open_id = $user->openid;

        $user_nickname = $user->nickname;
        $user_nickname = Util::json_name($user_nickname);

        $user_data_info = array(
            'user_openid' => $user->openid,
            'user_nickname' => $user_nickname,
            'user_sex' => $user->sex,
            'user_language' => $user->language,
            'user_city' => $user->city,
            'user_country' => $user->country,
            'user_province' => $user->province,
            'user_headimgurl' => $user->headimgurl,
            'status' => 1,
            'create_time' => time()
        );
        // 写入或者更新数据
        $user_db = $user_service->editUserByOpenId($user_data_info, $sid, $open_id);
        // 重新查询出来，带了数据库的id
        //$user_db = $user_service->getUserByOpenId($open_id);

        $user_info = $user_service->getUserBaseInfo($sid, $user_db->user_id);
        return $user_info;
    }


    /**
     * 返回会员的带参二维码
     *  {
     *       "code": 200,
     *       "data": {
     *          "ticket": "参数，这个二维码扫码的时候会传递给服务器端",
     *          "url": "二维码的内容",
     *          "qrcode_url": "下载二维码的URL"
     *   }
     * @param $sid
     * @param $uid
     * @return mixed
     */
    public function get_user_qrcode($sid, $uid)
    {
        $key = 'user_' . $uid;
        $res['code'] = 200;
        $result = $this->get_forever_qrcode($sid, $key);
        $res['data'] = $result;
        return $res;
    }

    /** 返回带参二维码
     *
     * @param $sid
     * @param $key
     * @return mixed
     */
    public function get_forever_qrcode($sid, $key)
    {
        $result = WeixinHelper::get_forever_qrcode($sid, $key);
        return $result;
    }

    /**
     * 获得分享签名
     * @param $sid
     * @param $url
     */
    public function get_share_params($sid, $url)
    {
        $js_array = WeixinHelper::get_share_params($sid, $url);
        return $js_array;
    }

    /**
     * 获得微信消息模板长id
     */
    public function get_template_id($sid, $template_short_no)
    {

        $result = WeixinHelper::get_template_id($sid, $template_short_no);
        return $result;
    }

    /**
     * 获取微信自定义菜单
     */
    public function get_menu($sid)
    {
        $menu = WeixinHelper::get_menu($sid);
        return $menu;

    }

    /**
     * 设置微信自定义菜单
     * @param $sid
     * @param $buttons    菜单
     * @param $matchRule  个性化菜单设置
     */
    public function set_menu($sid, $buttons, $matchRule = [])
    {

        if (!$matchRule) {
            // 如果不是个性化菜单，就先清掉菜单
            WeixinHelper::destroy_menu($sid);
        }
        $menu = WeixinHelper::set_menu($sid, $buttons, $matchRule);
        return $menu;

    }

    /**
     * 发送预览群发消息给指定的 openId 用户
     * @param $sid 店铺Id
     * @param $messageType 群发的消息类型，图文消息为mpnews，文本消息为text，语音为voice，音乐为music，图片为image，视频为video，卡券为wxcard
     * @param $message 消息内容 文本消息类型，所对应的为一个文本字符串；图文、语音、图片消息类型，所对应的为 media_id
     * 卡券消息类型，所对应的为 card_id；
     * 视频消息为两种情况：
     * - 视频消息类型，群发视频消息给**组或预览群发视频消息**给用户时所对应的 `$message` 为`media_id`
     * - 群发视频消息**给指定用户**时所对应的 `$message` 为一个数组 `['MEDIA_ID', 'TITLE', 'DESCRIPTION']`
     *
     * @param $openId
     */
    public function preview($sid, $messageType, $message, $openId)
    {
        $broadcast = WeixinHelper::preview($sid, $messageType, $message, $openId);
        return $broadcast;
    }

    /**
     * 上传永久文章内容图片
     * @param $sid
     * @param $path
     */
    public function upload_material_image($sid, $path)
    {

        $url = WeixinHelper::upload_material_image($sid, $path);
        return $url;
    }

    /**
     * 替换永久图文内容图片
     * @param $sid
     * @param $xstr
     * @return mixed
     */
    public function replace_material_image($sid, $xstr, $outer = 0)
    {
        // 匹配图片的src
        $img_pattern = "|<img[^>]+src=['\" ]?([^ '\"?]+)['\" >]|U";
        preg_match_all($img_pattern, $xstr, $img_out, PREG_SET_ORDER);
        if ($img_out) {
            foreach ($img_out as $k => $v) {
                $imgurl = $v[1];
                $outer = preg_match('/^http:/', $imgurl) ? 1 : 0;
                if ($outer == 1) {
                    $path = __DIR__ . '/../../../runtime/' . md5(date('YmdHis')) . '.jpg';
                    file_put_contents($path, file_get_contents($imgurl));
                } else {
                    $path = __DIR__ . '/../../../runtime' . $imgurl;
                }

                //获取上传图文内容中的图片地址
                $url = $this->upload_material_image($sid, $path);

                if ($url && $outer == 1) {
                    unlink($path);
                }

//                $xstr = str_replace($imgurl, $url, $xstr);
                $xstr = str_replace($imgurl, $url, $xstr);
            }
        }

        return $xstr;
    }

    /**
     * 上传图文缩略图
     * @param $sid
     * @param $path
     * @return mixed
     */
    public function upload_material_thumb($sid, $path)
    {
        $media_id = WeixinHelper::uploadThumb($sid, $path);
        return $media_id;
    }

    public function upload_material($sid, $article)
    {
        $result = WeixinHelper::uploadArticle($sid, $article);
        return $result;
    }

    /**
     * 群发消息给指定用户
     * @param $sid
     * @param $messageType
     * @param $message
     */
    public function mass_send($sid, $messageType, $message, $openIds = [])
    {
        return WeixinHelper::massSend($sid, $messageType, $message, $openIds);
    }

    /**
     * 获取用户列表
     * @param $sid
     * @return \EasyWeChat\Support\Collection
     */
    public function get_user_list($sid)
    {
        return WeixinHelper::getUserList($sid);
    }


    /**
     * 获取分享script
     * @param $sid 店铺Id
     * @param $uid 用户ID
     * @param $data_id 分享内容的索引Id（如分享内容页面，则为内容页面的索引ID）
     * @param $link 分享链接
     * @param $title 分享标题
     * @param $imgUrl 分享主图
     * @param $content 分享内容
     * @param $shareCfg 分享配置参数
     * @return mixed
     */
    public function get_share_script($shareInfo = [], $shareCfg = [], $shareLog = [])
    {
        $shareScript = "<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script>\n";
        $shareScript .= "<script>
			 window.shareData = {

			'timeLineLink': '" . $shareInfo['link'] . "',

			'tTitle': '" . $shareInfo['title'] . "',

			'tContent': '" . $shareInfo['content'] . "',

			'imgUrl': '" . $shareInfo['imgUrl'] . "',

			};
		</script>\n";

        $shareScript .= "<script>\n" .
            "wx.config(" . $shareCfg . ");

    function share_log(result, type, prop){
        if(result == 'success'){
            $.ajax({
                url : '" . $shareLog['postUrl'] . "',
                type : 'post',
                data : {
//                    'sid' : " . $shareLog['sid'] . ",
                    'uid' : " . $shareLog['uid'] . ",
                    'share_type' : result,
                    'message_type' : type,
                    'share_url' : window.location.href,
                    'data_id' : " . $shareLog['data_id'] . ",
                    'cid' : " . $shareLog['cid'] . ",
                    'm' : '" . $shareLog['m'] . "',
                    'c' : '" . $shareLog['c'] . "',
                    'a' : '" . $shareLog['a'] . "',
                }
            });
        }
    }

    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
        wx.checkJsApi({
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'hideOptionMenu',
                'hideMenuItems',
                'showMenuItems'
            ],
            success: function (res) {
            //alert(JSON.stringify(res));
            }
        });

        //wx.hideOptionMenu();
        // 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
        wx.onMenuShareAppMessage({
          title: shareData.tTitle,
          desc: shareData.tContent,
          link: shareData.timeLineLink+'&share_type=by_friend',
          imgUrl: shareData.imgUrl,
          trigger: function (res) {
            //alert('用户点击发送给朋友');
        share_log('trigger','朋友','');
          },
          success: function (res) {
            //alert('已分享');
        share_log('success','朋友','');
          },
          cancel: function (res) {
            //alert('已取消');
        share_log('cancel','朋友','');
          },
          fail: function (res) {
            //alert(JSON.stringify(res));
        share_log('fail','朋友',JSON.stringify(res));
          }
        });
      // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
        wx.onMenuShareTimeline({
          title: shareData.tTitle,
          desc: shareData.tContent,
          link: shareData.timeLineLink+'&share_type=by_friend_circle',
          imgUrl: shareData.imgUrl,
          trigger: function (res) {
            //alert('用户点击分享到朋友圈');
        share_log('trigger','朋友圈','');
          },
          success: function (res) {
            //alert('已分享');
        share_log('success','朋友圈','');
          },
          cancel: function (res) {
            //alert('已取消');
        share_log('cancel','朋友圈','');
          },
          fail: function (res) {
            //alert(JSON.stringify(res));
        share_log('fail','朋友圈',JSON.stringify(res));
          }
        });


      // 2.3 监听“分享到QQ”按钮点击、自定义分享内容及分享结果接口

        wx.onMenuShareQQ({
           title: shareData.tTitle,
          desc: shareData.tContent,
          link: shareData.timeLineLink+'&share_type=by_qq',
          imgUrl: shareData.imgUrl,
          trigger: function (res) {
            //alert('用户点击分享到QQ');
        share_log('trigger','QQ','');
          },
          complete: function (res) {
            //alert(JSON.stringify(res));
        share_log('complete','QQ','');
          },
          success: function (res) {
            //alert('已分享');
        share_log('success','QQ','');
          },
          cancel: function (res) {
            //alert('已取消');
        share_log('cancel','QQ','');
          },
          fail: function (res) {
            //alert(JSON.stringify(res));
        share_log('fail','QQ',JSON.stringify(res));
          }
        });


      // 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口

        wx.onMenuShareWeibo({
          title: shareData.tTitle,
          desc: shareData.tContent,
          link: shareData.timeLineLink+'&share_type=by_weibo',
          imgUrl: shareData.imgUrl,
          trigger: function (res) {
            //alert('用户点击分享到微博');
        share_log('trigger','微博','');
          },
          complete: function (res) {
            //alert(JSON.stringify(res));
        share_log('complete','微博','');
          },
          success: function (res) {
            //alert('已分享');
        share_log('share_log','微博','');
          },
          cancel: function (res) {
            //alert('已取消');
        share_log('cancel','微博','');
          },
          fail: function (res) {
            //alert(JSON.stringify(res));
        share_log('fail','微博',JSON.stringify(res));
          }
        });

        wx.hideMenuItems({
            menuList: [
                'menuItem:copyUrl' // 复制链接
            ],
            success: function (res) {
                //alert('hide copy url success');
            }
        });

    });

    wx.error(function (res) {
      alert(res.errMsg);
      share_log('errMsg','errMsg',res.errMsg);
    });

</script>";
        return $shareScript;
    }


    /**
     * 店铺是否配置过微信APPID和APPSECRET
     * @param $sid
     * @return bool
     */
    public function isSettingAPPIDAndAPPSECRET($sid)
    {
        $info = db('store_weixin')->where(['sid' => $sid])->find();
        if ($info['token'] && $info['appid'] && $info['appsecret']) {
            return true;
        } else {
            return false;
        }
    }


    /**
     *
     * 下载临时素材到本地
     * @param $sid
     * @param $media_id
     * @param $path
     * @param $file_name
     * @return string
     */
    public function download_temporary_media($sid, $media_id, $path, $file_name)
    {
        $result = WeixinHelper::downloadTemporaryMedia($sid, $media_id, $path, $file_name);
        return $result;
    }

    public function get_stream($sid, $media_id, $path, $file_name)
    {
        return WeixinHelper::getStream($sid, $media_id, $path, $file_name);
    }

    /**
     * 删除指定ID的模板
     * @param $sid
     * @param $template_no
     * @return \EasyWeChat\Support\Collection
     */
    public function delete_private_template($sid, $template_no)
    {
        $result = WeixinHelper::deletePrivateTemplate($sid, $template_no);
        if ($result->errcode == 0 && $result->errmsg == 'ok') {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取所有模板列表
     * @param $sid
     * @return mixed
     */
    public function get_private_templates($sid)
    {
        $result = WeixinHelper::getPrivateTemplates($sid);
        $result = json_decode($result, 1);
        $list = $result['template_list'];
        return $list;
    }


    /**
     * 根据模版ID获取模版信息
     * @param $sid
     * @param $template_id
     * @return bool
     */
    public function get_one_template($sid, $template_id)
    {
        $list = $this->get_private_templates($sid);
        if($list){
            foreach($list as $k => $v){
                if($v['template_id'] == $template_id){
                    return $v;
                }
            }
        }
        return false;
    }
}
